// 自行车外贸产品管理系统 - 连接真实数据库
class BicycleProductManager {
    constructor() {
        this.baseUrl = 'http://localhost:3000'; // 指向后端API端口
        this.products = [];
        this.currentLanguage = 'zh';
        this.editingProduct = null;
        this.currentImages = [];
        this.carouselImages = [];
        this.currentSlide = 0;
        this.carouselInterval = null;
        this.currentPage = 1;
        this.pageSize = 12;
        this.init();
    }

    async init() {
        await this.loadProducts();
        this.setupEventListeners();
        this.setupFormValidation();
        this.setupImageUpload();
        console.log('产品管理系统已初始化');
    }

    // 加载真实产品数据
    async loadProducts() {
        try {
            const response = await fetch(`${this.baseUrl}/products?page=${this.currentPage}&limit=${this.pageSize}`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            if (result.success) {
                this.products = result.data.products || [];
                this.renderProducts();
                this.renderPagination(result.data.total || 0);
            } else {
                this.showNotification('加载产品失败: ' + result.message, 'error');
                this.renderEmptyState();
            }
        } catch (error) {
            console.error('加载产品失败:', error);
            this.showNotification('网络错误，请检查后端服务是否启动', 'error');
            this.renderEmptyState();
        }
    }

    // 保存产品到数据库
    async saveProductToDatabase(productData, isUpdate = false) {
        try {
            const url = isUpdate ? 
                `${this.baseUrl}/products/${productData.id}` : 
                `${this.baseUrl}/products`;
            
            const method = isUpdate ? 'PUT' : 'POST';
            
            const response = await fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(productData)
            });

            const result = await response.json();
            return result;
        } catch (error) {
            console.error('保存产品失败:', error);
            throw error;
        }
    }

    // 渲染产品列表
    renderProducts() {
        const grid = document.getElementById('productsGrid');
        
        if (this.products.length === 0) {
            grid.innerHTML = `
                <div style="grid-column: 1 / -1; text-align: center; padding: 60px 20px; color: #666;">
                    <i class="fas fa-bicycle" style="font-size: 48px; margin-bottom: 20px;"></i>
                    <h3>暂无产品</h3>
                    <p>点击"新增产品"按钮开始添加您的自行车产品</p>
                </div>
            `;
            return;
        }

        grid.innerHTML = this.products.map(product => this.createProductCard(product)).join('');
    }

    // 渲染分页
    renderPagination(totalItems) {
        const totalPages = Math.ceil(totalItems / this.pageSize);
        const paginationContainer = document.createElement('div');
        paginationContainer.className = 'pagination';
        paginationContainer.style.cssText = `
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: 30px;
            padding: 20px;
        `;
        
        if (totalPages <= 1) {
            return;
        }

        let paginationHtml = '';
        
        // 上一页
        if (this.currentPage > 1) {
            paginationHtml += `<button class="btn btn-secondary" onclick="productManager.goToPage(${this.currentPage - 1})">上一页</button>`;
        }

        // 页码
        for (let i = 1; i <= totalPages; i++) {
            if (i === this.currentPage) {
                paginationHtml += `<button class="btn btn-primary">${i}</button>`;
            } else if (i >= this.currentPage - 2 && i <= this.currentPage + 2) {
                paginationHtml += `<button class="btn btn-secondary" onclick="productManager.goToPage(${i})">${i}</button>`;
            }
        }

        // 下一页
        if (this.currentPage < totalPages) {
            paginationHtml += `<button class="btn btn-secondary" onclick="productManager.goToPage(${this.currentPage + 1})">下一页</button>`;
        }

        paginationContainer.innerHTML = paginationHtml;
        
        // 添加到页面
        const container = document.querySelector('.products-container');
        const existingPagination = container.querySelector('.pagination');
        if (existingPagination) {
            existingPagination.remove();
        }
        container.appendChild(paginationContainer);
    }

    // 跳转到指定页面
    async goToPage(page) {
        this.currentPage = page;
        await this.loadProducts();
    }

    createProductCard(product) {
        const totalStock = (product.stock_domestic || 0) + (product.stock_overseas || 0);
        const isLowStock = totalStock <= (product.safety_stock || 10);
        const displayName = product.name_zh || product.name_en || '未命名产品';
        const displayDescription = product.description_zh || product.description_en || '';
        
        return `
            <div class="product-card" data-product-id="${product.id}">
                <div class="product-image" onclick="productManager.viewProductDetails(${product.id})" style="cursor: pointer;">
                    ${product.image_url ? 
                        `<img src="${product.image_url}" alt="${displayName}" style="width: 100%; height: 100%; object-fit: cover; border-radius: 4px;">` : 
                        `<i class="fas fa-bicycle" style="font-size: 48px; color: #ccc;"></i>`
                    }
                </div>
                
                <div class="product-title">${displayName}</div>
                
                ${displayDescription ? `
                <div style="font-size: 14px; color: #666; margin-bottom: 10px; line-height: 1.4;">
                    ${displayDescription.length > 100 ? displayDescription.substring(0, 100) + '...' : displayDescription}
                </div>
                ` : ''}
                
                <div class="product-specs">
                    <div><strong>SKU:</strong> ${product.sku}</div>
                    <div><strong>型号:</strong> ${product.model}</div>
                    <div><strong>材质:</strong> ${this.getMaterialName(product.frame_material)}</div>
                    <div><strong>尺寸:</strong> ${product.frame_size}</div>
                </div>
                
                <div class="product-price">
                    <div class="price-main">$${product.price_usd}</div>
                    <div class="price-secondary">
                        €${product.price_eur} / £${product.price_gbp}
                    </div>
                </div>
                
                <div style="margin-bottom: 15px;">
                    <div style="display: flex; justify-content: space-between; font-size: 12px; color: #666;">
                        <span>国内仓: ${product.stock_domestic || 0}</span>
                        <span>海外仓: ${product.stock_overseas || 0}</span>
                    </div>
                    ${isLowStock ? '<div class="inventory-warning"><i class="fas fa-exclamation-triangle"></i> 库存预警</div>' : ''}
                </div>
                
                <div class="certification-badges" style="margin-bottom: 15px;">
                    ${product.certifications?.map(cert => 
                        `<span class="cert-badge">${this.getCertificationName(cert)}</span>`
                    ).join('') || ''}
                </div>
                
                <div class="product-actions">
                    <button class="btn btn-primary" onclick="productManager.editProduct(${product.id})" style="flex: 1;">
                        <i class="fas fa-edit"></i> 编辑
                    </button>
                    <button class="btn btn-warning" onclick="productManager.duplicateProduct(${product.id})">
                        <i class="fas fa-copy"></i>
                    </button>
                    <button class="btn btn-danger" onclick="productManager.deleteProduct(${product.id})">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `;
    }

    getMaterialName(material) {
        const materials = {
            'aluminum': '铝合金',
            'carbon': '碳纤维',
            'steel': '钢架',
            'titanium': '钛合金'
        };
        return materials[material] || material;
    }

    getCertificationName(cert) {
        const certs = {
            'ce': 'CE',
            'cpsc': 'CPSC',
            'rohs': 'RoHS'
        };
        return certs[cert] || cert;
    }

    // 设置事件监听器
    setupEventListeners() {
        const searchInput = document.getElementById('searchInput');
        let searchTimeout;
        
        searchInput.addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                this.searchProducts(e.target.value);
            }, 500);
        });

        const form = document.getElementById('productForm');
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            this.saveProduct();
        });

        // 价格自动换算
        this.setupPriceConversion();
    }

    // 图片上传功能
    setupImageUpload() {
        const imageUpload = document.getElementById('imageUpload');
        const imagePreview = document.getElementById('imagePreview');

        imageUpload.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                this.handleImageUpload(file);
            }
        });

        // 点击预览区域触发文件选择
        imagePreview.addEventListener('click', () => {
            imageUpload.click();
        });
    }

    handleImageUpload(file) {
        // 检查文件类型
        if (!file.type.startsWith('image/')) {
            this.showNotification('请选择图片文件', 'error');
            return;
        }

        // 检查文件大小（限制5MB）
        if (file.size > 5 * 1024 * 1024) {
            this.showNotification('图片大小不能超过5MB', 'error');
            return;
        }

        const reader = new FileReader();
        reader.onload = (e) => {
            const imageUrl = e.target.result;
            this.displayImagePreview(imageUrl);
            document.getElementById('imageUrl').value = imageUrl;
            this.currentImages = [imageUrl]; // 存储图片URL
        };
        reader.readAsDataURL(file);
    }

    displayImagePreview(imageUrl) {
        const imagePreview = document.getElementById('imagePreview');
        imagePreview.innerHTML = `
            <img src="${imageUrl}" alt="产品图片预览" style="max-width: 100%; max-height: 100%; object-fit: cover;">
            <div style="position: absolute; bottom: 5px; right: 5px; background: rgba(0,0,0,0.7); color: white; padding: 2px 5px; border-radius: 3px; font-size: 12px;">
                <i class="fas fa-sync-alt" onclick="productManager.rotateImage()" style="cursor: pointer; margin-right: 5px;"></i>
                <i class="fas fa-trash" onclick="productManager.removeImage()" style="cursor: pointer;"></i>
            </div>
        `;
    }

    rotateImage() {
        // 简单的图片旋转功能（演示用）
        const img = document.querySelector('#imagePreview img');
        if (img) {
            const currentRotation = parseInt(img.style.transform.replace('rotate(', '').replace('deg)', '')) || 0;
            img.style.transform = `rotate(${currentRotation + 90}deg)`;
        }
    }

    removeImage() {
        const imagePreview = document.getElementById('imagePreview');
        imagePreview.innerHTML = `
            <i class="fas fa-camera" style="font-size: 48px; color: #ccc;"></i>
            <span>点击上传产品图片</span>
        `;
        document.getElementById('imageUrl').value = '';
        this.currentImages = [];
    }

    // 搜索产品
    async searchProducts(query) {
        if (!query.trim()) {
            await this.loadProducts();
            return;
        }

        try {
            const response = await fetch(`${this.baseUrl}/products/search?q=${encodeURIComponent(query)}`);
            const result = await response.json();
            
            if (result.success) {
                this.products = result.data.products || [];
                this.renderProducts();
                this.renderPagination(result.data.total || 0);
            } else {
                this.showNotification('搜索失败: ' + result.message, 'error');
            }
        } catch (error) {
            console.error('搜索产品失败:', error);
            this.showNotification('搜索失败，请检查网络连接', 'error');
        }
    }

    // 价格自动换算
    setupPriceConversion() {
        const usdInput = document.querySelector('input[name="price_usd"]');
        const eurInput = document.querySelector('input[name="price_eur"]');
        const gbpInput = document.querySelector('input[name="price_gbp"]');

        if (usdInput) {
            usdInput.addEventListener('input', (e) => {
                const usdValue = parseFloat(e.target.value);
                if (!isNaN(usdValue)) {
                    if (eurInput) eurInput.value = (usdValue * 0.92).toFixed(2);
                    if (gbpInput) gbpInput.value = (usdValue * 0.79).toFixed(2);
                }
            });
        }
    }

    // 表单验证
    setupFormValidation() {
        const form = document.getElementById('productForm');
        const inputs = form.querySelectorAll('input[required]');
        
        inputs.forEach(input => {
            input.addEventListener('blur', () => {
                this.validateField(input);
            });
        });
    }

    validateField(field) {
        if (!field.value.trim()) {
            field.style.borderColor = '#dc3545';
            return false;
        }
        field.style.borderColor = '#28a745';
        return true;
    }

    // 产品操作
    openProductModal(product = null) {
        this.editingProduct = product;
        const modal = document.getElementById('productModal');
        const title = document.getElementById('modalTitle');
        
        title.textContent = product ? '编辑产品' : '新增产品';
        
        if (product) {
            this.fillForm(product);
        } else {
            this.clearForm();
        }
        
        modal.style.display = 'block';
    }

    closeProductModal() {
        document.getElementById('productModal').style.display = 'none';
        this.editingProduct = null;
    }

    fillForm(product) {
        const form = document.getElementById('productForm');
        
        // 基础信息
        form.sku.value = product.sku || '';
        form.model.value = product.model || '';
        
        // 中文信息
        form.name_zh.value = product.name_zh || '';
        form.description_zh.value = product.description_zh || '';
        form.features_zh.value = product.features_zh || '';
        
        // 英文信息
        form.name_en.value = product.name_en || '';
        form.description_en.value = product.description_en || '';
        
        // 图片显示
        if (product.image_url) {
            this.displayImagePreview(product.image_url);
            document.getElementById('imageUrl').value = product.image_url;
            this.currentImages = [product.image_url];
        } else {
            this.removeImage();
        }
        
        // 规格
        form.frame_material.value = product.frame_material || '';
        form.frame_size.value = product.frame_size || '';
        form.max_weight.value = product.max_weight || '';
        form.wheel_size.value = product.wheel_size || '';
        
        // 外贸合规
        form.hs_code.value = product.hs_code || '';
        form.origin.value = product.origin || '';
        form.ce_certified.checked = product.certifications?.includes('ce') || false;
        form.cpsc_certified.checked = product.certifications?.includes('cpsc') || false;
        form.rohs_certified.checked = product.certifications?.includes('rohs') || false;
        
        // 价格库存
        form.price_usd.value = product.price_usd || '';
        form.price_eur.value = product.price_eur || '';
        form.price_gbp.value = product.price_gbp || '';
        form.stock_domestic.value = product.stock_domestic || '';
        form.stock_overseas.value = product.stock_overseas || '';
        form.safety_stock.value = product.safety_stock || 10;
        
        // 物流
        form.weight.value = product.weight || '';
        form.package_size.value = product.package_size || '';
        form.shipping_dhl.checked = product.shipping_methods?.includes('dhl') || false;
        form.shipping_ups.checked = product.shipping_methods?.includes('ups') || false;
        form.shipping_sea.checked = product.shipping_methods?.includes('sea') || false;
        form.banned_countries.value = product.banned_countries?.join('\n') || '';
    }

    clearForm() {
        const form = document.getElementById('productForm');
        form.reset();
        form.safety_stock.value = 10;
    }

    // 保存产品
    async saveProduct() {
        const form = document.getElementById('productForm');
        const formData = new FormData(form);
        
        // 收集认证信息
        const certifications = [];
        if (formData.get('ce_certified')) certifications.push('ce');
        if (formData.get('cpsc_certified')) certifications.push('cpsc');
        if (formData.get('rohs_certified')) certifications.push('rohs');
        
        // 收集物流方式
        const shippingMethods = [];
        if (formData.get('shipping_dhl')) shippingMethods.push('dhl');
        if (formData.get('shipping_ups')) shippingMethods.push('ups');
        if (formData.get('shipping_sea')) shippingMethods.push('sea');
        
        const productData = {
            sku: formData.get('sku'),
            model: formData.get('model'),
            
            // 中文信息
            name_zh: formData.get('name_zh'),
            description_zh: formData.get('description_zh'),
            features_zh: formData.get('features_zh'),
            
            // 英文信息
            name_en: formData.get('name_en'),
            description_en: formData.get('description_en'),
            
            // 图片信息
            image_url: formData.get('image_url'),
            
            // 规格信息
            frame_material: formData.get('frame_material'),
            frame_size: formData.get('frame_size'),
            max_weight: parseFloat(formData.get('max_weight')) || 0,
            wheel_size: formData.get('wheel_size'),
            
            // 外贸合规
            hs_code: formData.get('hs_code'),
            origin: formData.get('origin'),
            certifications: certifications,
            
            // 价格库存
            price_usd: parseFloat(formData.get('price_usd')) || 0,
            price_eur: parseFloat(formData.get('price_eur')) || 0,
            price_gbp: parseFloat(formData.get('price_gbp')) || 0,
            stock_domestic: parseInt(formData.get('stock_domestic')) || 0,
            stock_overseas: parseInt(formData.get('stock_overseas')) || 0,
            safety_stock: parseInt(formData.get('safety_stock')) || 10,
            
            // 物流信息
            weight: parseFloat(formData.get('weight')) || 0,
            package_size: formData.get('package_size'),
            shipping_methods: shippingMethods,
            banned_countries: formData.get('banned_countries').split('\n').filter(c => c.trim()),
            
            status: 'active'
        };
        
        // 验证必填字段
        if (!productData.sku || !productData.name_zh || !productData.name_en) {
            this.showNotification('请填写SKU、中文名称和英文名称', 'error');
            return;
        }
        
        try {
            const isUpdate = !!this.editingProduct;
            const result = await this.saveProductToDatabase(productData, isUpdate);
            
            if (result.success) {
                this.showNotification('产品保存成功!', 'success');
                this.closeProductModal();
                await this.loadProducts(); // 重新加载产品列表
            } else {
                this.showNotification('保存失败: ' + result.message, 'error');
            }
        } catch (error) {
            console.error('保存产品失败:', error);
            this.showNotification('网络错误，保存失败', 'error');
        }
    }

    editProduct(id) {
        // 跳转到独立编辑页面
        window.location.href = `edit-product.html?id=${id}`;
    }

    duplicateProduct(id) {
        const product = this.products.find(p => p.id === id);
        if (product) {
            const duplicated = {
                ...JSON.parse(JSON.stringify(product)),
                id: this.generateId(),
                sku: product.sku + '-COPY',
                created_at: new Date().toISOString()
            };
            this.products.unshift(duplicated);
            this.saveProducts();
            this.renderProducts();
            this.showNotification('产品复制成功!', 'success');
        }
    }

    deleteProduct(id) {
        if (confirm('确定要删除这个产品吗？此操作不可撤销。')) {
            this.products = this.products.filter(p => p.id !== id);
            this.saveProducts();
            this.renderProducts();
            this.showNotification('产品删除成功!', 'success');
        }
    }

    generateId() {
        return Math.max(...this.products.map(p => p.id), 0) + 1;
    }

    // 批量操作
    exportProducts() {
        const dataStr = JSON.stringify(this.products, null, 2);
        const dataBlob = new Blob([dataStr], { type: 'application/json' });
        const url = URL.createObjectURL(dataBlob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `bicycle-products-${new Date().toISOString().split('T')[0]}.json`;
        link.click();
        URL.revokeObjectURL(url);
    }

    importProducts() {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.json';
        input.onchange = (e) => {
            const file = e.target.files[0];
            const reader = new FileReader();
            reader.onload = (event) => {
                try {
                    const imported = JSON.parse(event.target.result);
                    this.products = imported;
                    this.saveProducts();
                    this.renderProducts();
                    this.showNotification('产品导入成功!', 'success');
                } catch (error) {
                    this.showNotification('导入失败: 文件格式错误', 'error');
                }
            };
            reader.readAsText(file);
        };
        input.click();
    }

    // 多语言切换
    switchLanguage(lang) {
        this.currentLanguage = lang;
        document.querySelectorAll('.language-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        event.target.classList.add('active');
        
        // 切换语言内容显示
        this.toggleLanguageContent(lang);
        this.showNotification(`切换到${this.getLanguageName(lang)}`, 'info');
    }

    toggleLanguageContent(lang) {
        // 隐藏所有语言内容
        document.querySelectorAll('.language-content').forEach(content => {
            content.style.display = 'none';
        });
        
        // 显示当前语言内容
        const currentContent = document.getElementById(`${lang}-content`);
        if (currentContent) {
            currentContent.style.display = 'block';
        }
    }

    getLanguageName(lang) {
        const languages = {
            'zh': '中文',
            'en': '英文',
            'de': '德语',
            'fr': '法语',
            'es': '西班牙语'
        };
        return languages[lang] || lang;
    }

    showNotification(message, type = 'info') {
        // 简单的通知实现
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 4px;
            color: white;
            z-index: 10000;
            font-weight: bold;
            background: ${type === 'success' ? '#28a745' : type === 'error' ? '#dc3545' : '#007bff'};
        `;
        notification.textContent = message;
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }
}

// 全局函数
function openProductModal() {
    productManager.openProductModal();
}

function closeProductModal() {
    productManager.closeProductModal();
}

function switchLanguage(lang) {
    productManager.switchLanguage(lang);
}

function exportProducts() {
    productManager.exportProducts();
}

function importProducts() {
    productManager.importProducts();
}

// 初始化
const productManager = new BicycleProductManager();

// 点击模态框外部关闭
window.onclick = function(event) {
    const modal = document.getElementById('productModal');
    if (event.target === modal) {
        closeProductModal();
    }
}